package org.itboys.mobile.service.mongo.mobile;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;

import org.itboys.kitchen.entity.mongo.village.KitchenVillage;
import org.itboys.kitchen.service.mongo.village.KitchenVillageService;
import org.itboys.kitchen.util.MobileSignUtils;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayAddress;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.Sun;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_收获地址_service_移动端
 */
@Service
public class SundayMobileAddressService extends BaseMongoService<SundayAddress>{
    @Autowired
    private KitchenVillageService villageService;
    @Autowired
    private SundayMemberService memberService;
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayAddress> getEntityClass() {
        return SundayAddress.class;
    }

    /**
     * 获取用户所有收货地址
     * @param memberId
     * @return
     */
    public List<SundayAddress> selectAddress(Long memberId){
        Map<String,Object> param =new HashMap<String, Object>();
        param.put("memberId", memberId);
        param.put("isDeleted", SundayCommonConstants.NO);
        //有限排序默认地址
        param.put("sort","isDefault");
        param.put("order","DESC");
        SundayMember member=memberService.getById(memberId);
        List<SundayAddress> adds = super.list(param);
        for(SundayAddress add:adds){
            if(member.getUserType()== SundayCommonConstants.user_type_member){
                add.setReceiveAddress(add.getDistrictName()+add.getVillageName()+add.getReceiveAddress());
            }else{
                add.setReceiveName(add.getCityName()+add.getDistrictName()+add.getReceiveAddress());
            }


        }
        return adds;
    }

    /**
     * 新增收货地址(用户版和管理版)。农厨版本收货地址：用户：传入小区ID；门店（大客户）：传入省市区
     * @param id
     * @param memberId
     * @param villageId
     * @param receiveName
     * @param receiveMobile
     * @param provinceId
     * @param provinceName
     * @param cityId
     * @param cityName
     * @param districtId
     * @param districtName
     * @param receiveAddress
     */
    public void saveAddress(Long id,Long memberId,Long villageId,String receiveName,String receiveMobile,
                            Long provinceId, String provinceName, Long cityId, String cityName, Long districtId, String districtName,
                            String receiveAddress){
      /*  //2017年6月20日，新增，验证签名
        Map<String, Object> param =new HashMap<String,Object>();
        param.put("id",id);
        param.put("villageId",villageId);
        param.put("receiveName",receiveName);
        param.put("receiveMobile",receiveMobile);
        param.put("provinceId",provinceId);
        param.put("provinceName",provinceName);
        param.put("cityId",cityId);
        param.put("cityName",cityName);
        param.put("districtId",districtId);
        param.put("districtName",districtName);
        param.put("receiveAddress",receiveAddress);
        param.put("nonce", nonce);
        param.put("sign", sign);
        boolean signSer = MobileSignUtils.signCheck(param, sign);
        if(!signSer){
            logger.warn("签名校验失败");
            throw new ErrorException("签名校验失败");
        }*/

        KitchenVillage village=new KitchenVillage();
        if(LongUtil.isNotZreo(villageId)){
            village=villageService.getById(villageId);
            provinceId=village.getProvinceId();
            provinceName=village.getProvinceName();
            cityId=village.getCityId();
            cityName=village.getCityName();
            districtId=village.getDistrictId();
            districtName=village.getDistrictName();
        }
        if(id==null||id==0l){
                SundayAddress address=new SundayAddress(
                        id,memberId,villageId,village.getName(), receiveName,receiveMobile,
                        provinceId, provinceName,cityId,cityName,districtId,districtName,
                        receiveAddress,SundayCommonConstants.NO);
                super.save(address);

        }else {
                super.updateExceptEmpty(id,new SundayAddress(id,memberId,villageId,village.getName(),receiveName,receiveMobile,provinceId, provinceName,cityId,cityName,districtId,districtName,receiveAddress, SundayCommonConstants.NO));
        }
    }

    /**
     * 设置默认地址
     * @param addressId
     * @param memberId
     */
    public void setDefaultAddress(Long addressId,Long memberId){
        //2017年6月20日，新增，验证签名
        Map<String, Object> param =new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("memberId",memberId);
        List<SundayAddress> addresses = super.list(param);
        for(SundayAddress address:addresses){
            if(address.getId()==addressId){
                address.setIsDefault(SundayCommonConstants.YES);
                super.updateExceptEmpty(address.getId(),address);
            }else{
                address.setIsDefault(SundayCommonConstants.NO);
                super.updateExceptEmpty(address.getId(),address);
            }
        }
    }
    /**
     * 删除收货地址
     * @param addressId
     * @param memberId
     */
    public void deleteAddress(Long addressId,Long memberId,String nonce, String sign){
        //2017年6月20日，新增，验证签名
        Map<String, Object> param =new HashMap<String,Object>();
        param.put("addressId",addressId);
        param.put("nonce", nonce);
        param.put("sign", sign);
        boolean signSer = MobileSignUtils.signCheck(param, sign);
        if(!signSer){
            logger.warn("签名校验失败");
            throw new ErrorException("签名校验失败");
        }
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("memberId",memberId);

        List<SundayAddress> addresses = super.list(param);
        //农厨项目需要用户保留至少一个收货地址（小区）；
        if(ListUtil.isNotNull(addresses)&&addresses.size()==1){
            throw new ErrorException("请至少保留一个收货地址（小区）");
        }
        super.update(addressId,"isDeleted",SundayCommonConstants.YES);
    }

}
